<template>
	<view class="x-list-content">
		<view class="x-page-border-top"></view>
		<template v-if="isLoading">
			<x-loading></x-loading>
		</template>
		<template v-else-if="!isLoading && addressList.length>0">
			<scroll-view scroll-y="true" :style="{height:(device.windowHeight-device.footerHeight)+'px'}">
				<template v-for="(item,index) in addressList">
					<view :class="[itemClasses[index], 'element']" @click="selecteAddress(item)">
						<view class="info">
							<view class="address x-text-multi">
								{{getAddressDesc(item.addressName, item.addressDetail)}}
							</view>
							<view class="detail">
								<span class="default" v-if="item.defaultAddress">默认</span>
								<span class="name"
									v-if="item.receiptName && item.receiptName.length>0">{{item.receiptName}}</span>
								<span class="contact" v-if="item.mobile && item.mobile.length>0">{{item.mobile}}</span>
							</view>
						</view>
						<view class="edit">
							<u-icon customStyle="padding: 20rpx;" @click.native.stop="editAddress(item)" name="edit-pen"
								:color="xIconColor()" size="24"></u-icon>
							<u-icon customStyle="marginLeft:20rpx; padding: 20rpx;" @click.native.stop="del(item)"
								name="trash" :color="xIconColor()" size="24"></u-icon>
						</view>
					</view>
					<view v-if="index==addressList.length-1" class="x-list-bottom-seperate-line"></view>
				</template>
			</scroll-view>
			<x-footer>
				<button class="x-btn" style="width:710rpx;border: 'none'; border-radius: 44rpx;"
					@click="()=>editAddress()">新建收货地址</button>
			</x-footer>
		</template>
		<template v-else>
			<x-empty class="x-empty" :height="device.windowHeight-device.footerHeight"></x-empty>
			<x-footer>
				<button class="x-btn" style="width:710rpx;border: 'none'; border-radius: 44rpx;"
					@click="()=>editAddress()">新建收货地址</button>
			</x-footer>
		</template>
	</view>
</template>

<script>
	import {
		getAddress,
		deleteById
	} from '@/api/address.js'
	import config from '@/config/index.js'
	import EventBusMacro from '@/plugins/EventBus/eventBusMacro.js'
	import {
		mapState
	} from 'vuex'
	import {
		ThemeMixin
	} from '@/mixins/theme/xThemeMixin.js'

	export default {
		mixins: [ThemeMixin],
		computed: {
			...mapState(['device']),
			itemClasses: function() {
				return this.addressList.map((item, index) => {
					if (index === 0) {
						return 'x-list-item-first';
					} else if (index === this.addressList.length - 1) {
						return 'x-list-item-last';
					} else {
						return 'x-list-item';
					}
				});
			},
		},
		components: {
			// XEmpty,
			// XFooter,
		},
		data() {
			return {
				userInfo: {},
				orderInfo: {},
				isShow: false,
				addressList: [],
				isSelected: false,
				isLoading: true,
			};
		},
		mounted() {
			this.loadData();
			this.$events.on(EventBusMacro.EB_EDIT_ADDRESS_INFO, this.onEditAddressInfo)
		},
		beforeDestroy(){
			this.$events.off(EventBusMacro.EB_EDIT_ADDRESS_INFO, this.onEditAddressInfo)
		},
		onLoad(options) {
			this.isSelected = options.isSelected || false;
		},
		methods: {
			onEditAddressInfo(){
				console.log("onEditAddressInfo is called")
				this.loadData()
			},
			getAddressDesc(addressName, addressDetail) {
				if (!addressName || addressName?.length <= 0) {
					return ''
				}
				let result = addressName.replace(/,/g, '') + addressDetail
				return result;
			},
			editAddress(index) {
				if (index) {
					uni.navigateTo({
						url: `/pages/mine/address/edit?info=${JSON.stringify(index)}`
					});
				} else {
					uni.navigateTo({
						url: `/pages/mine/address/edit`
					});
				}
			},
			// 选择地址
			selecteAddress(e) {
				if (!this.isSelected) {
					return false;
				}

				this.$events.emit(EventBusMacro.EB_ADDRESS_CHANGE, e);

				// uni.setStorageSync('address', e);
				uni.navigateBack()
			},
			//我的地址
			loadData(e) {
				console.log("loadData e=", e)

				this.isLoading = true
				this.$showLoading()
				getAddress().then(res => {
					this.isLoading = false
					this.$hideLoading()

					const list = new Array();

					let foundDefaultAddress = false
					console.log("res= ", res)
					// for(let t=0; t<5; ++t) {
					res.forEach(item => {
						const i = item;
						i.address = item.address
						console.log(i)
						list.push(i)

						if (item.defaultAddress == 1) {
							foundDefaultAddress = true
							if (!uni.getStorageSync('address')) {
								// 如果本地没有存放默认地址信息，同时发现存在有默认地址，直接发送默认地址出去
								this.$events.emit(EventBusMacro.EB_ADDRESS_CHANGE, item);
							}
							uni.setStorageSync('address', item);
						}
					})
					// }

					// 没有默认地址就置为空
					if (!foundDefaultAddress) {
						uni.setStorageSync('address', null);
					}

					this.addressList = list;
					console.log("this.addresslist=", this.addressList)
				}).catch(err => {
					this.isLoading = false
					this.$hideLoading()
				})
			},

			// 删除地址
			del(e) {
				uni.showModal({
					content: '确定要删除这个地址吗？',
					title: '提示',
					success: (res) => {
						if (res.confirm) {
							deleteById(e.id).then(res => {
								this.loadData()
								uni.showToast({
									title: '地址删除成功',
									icon: 'none'
								})
							})
						}
					}
				})
			},
		}
	};
</script>

<style lang="scss" scoped>
	@import "@/mixins/theme/xTheme.scss";

	.element {
		display: flex;
		justify-content: space-between;
		align-items: center;
		padding: 20rpx;

		.info {

			.address {
				font-size: 23rpx;
				font-family: PingFangSC-Semibold, PingFang SC;
				font-weight: 600;
				color: #000000;
				line-height: 33rpx;
			}

			.detail {
				display: flex;
				margin-top: 15rpx;

				.default {
					width: 46rpx;
					height: 33rpx;
					font-size: 23rpx;
					font-family: PingFang-SC-Medium;
					font-weight: 500;
					color: #FFFFFF;
					line-height: 33rpx;
					background-color: #{$x-theme-color}#{$x-theme-alpha};
					padding: 2rpx 4rpx;
					border-radius: 6rpx;
					margin-right: 4rpx;
				}

				.name {
					font-size: 23rpx;
					font-family: PingFangSC-Regular, PingFang SC;
					font-weight: 400;
					color: #8E8E8E;
					line-height: 33rpx;
					margin-right: 4rpx;
				}

				.contact {
					font-size: 23rpx;
					font-family: PingFangSC-Regular, PingFang SC;
					font-weight: 400;
					color: #8E8E8E;
					line-height: 33rpx;
				}
			}
		}

		.edit {
			display: flex;
			align-items: center;
		}
	}
</style>